<!--
* description: 展车订单制作
* author: wangjuan
* createdDate:2020-11-12
-->
<template>
  <div class="app-container app-container-table">
    <one-table-template
      ref="multipleTable"
      :dynamic-buttons="tableButtons"
      :dynamic-components="tableComponents"
      :dynamic-table-cols="tableCols"
      :dynamic-api-config="apiConfig"
      :dynamic-form-fields="formField"
      :dynamic-is-show-select="true"
      :dynamic-is-show-more-btn="true"
      :callback-obj="callbackObj"
    />

    <edit
      ref="editRef"
      :key="editPopupsKey"
      :dynamic-edit-row-data="editRowData"
      :popups-visible.sync="showPopupsVisible"
      :popups-state="editPopupsState"
    />
    <viewData
      ref="view"
      :key="viewPopupsKey"
      :dynamic-edit-row-data="viewRowData"
      :popups-visible.sync="viewPopupsVisible"
      :popups-state="editPopupsState"
      @closeviewData="closeviewData"
    />
  </div>
</template>
<script>
import { oneTableWithViewTemplateMixins } from '@/components/mixins/oneTableWithViewTemplateMixins'
import OneTableTemplate from '@/components/templates/oneTable'
import Vue from 'vue'
import api from '@/api/belowInfo'
import viewData from './viewData'

export default {
  name: 'BelowOrdCreate',

  components: {
    OneTableTemplate,
    viewData,
    Edit: () => import('./edit')
  },

  // 组件混入对象：{data[listQuery] methods[queryTable]}
  mixins: [oneTableWithViewTemplateMixins],

  // 阻塞路由预加载网格中组件的数据
  beforeRouteEnter(to, from, next) {
    Vue.prototype.$ConfigCache.CacheConfig.initData([to.path, 'belowOrd-Edit'], function() {
      next()
    })
  },

  data() {
    // 页面标识（与上面beforeRouteEnter中的对应）
    const viewPageCode = this.$route.path
    // 绑定事件配置化事件
    this.$ConfigCache.CacheConfig.bindEvent(this, [viewPageCode])

    return {
      viewPopupsKey: '',
      viewRowData: {},
      viewPopupsVisible: false,

      editPopupsKey: 'edit',
      selectRow: [],
      editRowData: {},
      showPopupsVisible: false,

      // 是否使用刷新Key的方式刷新弹窗
      resetDialogKey: false,

      // 网格查询API配置对象
      apiConfig: api.queryExhibitionCarProduction,

      // 动态组件-按钮
      tableButtons: [
        {
          compKey: 'btnKey1',
          type: 'primary',
          size: 'small',
          name: 'search',
          clickEvent: () => this.queryTable(1),
          text: this.$t('sys.button.query'), // 查询
          position: 'right',
          fuzzySearch: true
        },
        {
          compKey: 'btnKey2',
          size: 'small',
          name: 'reset',
          clickEvent: () => this.reset(),
          text: this.$t('sys.button.reset'),
          position: 'right' // 重置
        },
        {
          compKey: 'btnKey3',
          size: 'small',
          name: 'add',
          clickEvent: () => this.add(),
          text: this.$t('sys.button.add'),
          position: 'left'
        },
        {
          compKey: 'btnKey4',
          size: 'small',
          name: 'fabu',
          clickEvent: this.issue,
          text: '发布',
          position: 'left',
          disabled: true
        },
        {
          compKey: 'btnKey5',
          size: 'small',
          name: 'cancel',
          clickEvent: this.invalid,
          text: '作废',
          position: 'left',
          disabled: true
        }
      ],

      // 动态组件-查询条件
      tableComponents:
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path] &&
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path]
          .tableComponents &&
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path]
          .tableComponents.length > 0
          ? this.$ConfigCache.CacheConfig.cacheData[this.$route.path]
            .tableComponents
          : [
            // 显示组件
            {
              compKey: 'compKey1',
              labelName: '批次编号：',
              codeField: 'transferOrderCode',
              component: () => import('@/components/org/commonInput'),
              type: 'inputText',
              isMul: false,
              isMust: true
            },
            {
              compKey: 'compKey2',
              labelName: '负责人姓名：',
              codeField: 'chargeMen',
              component: () => import('@/components/org/commonInput'),
              type: 'inputText',
              isMul: false,
              isMust: true
            },
            {
              compKey: 'compKey3',
              labelName: '负责人电话：',
              codeField: 'chargePhone',
              component: () => import('@/components/org/commonInput'),
              type: 'inputText',
              validrule: { isPhone: true, noRequire: false, maxlength: 11 },
              isMul: false,
              isMust: true
            },
            {
              compKey: 'compKey4',
              labelName: '订单状态：',
              codeField: 'orderState',
              lookuptype: 'VE1129',
              component: () => import('@/components/org/LookupValue'),
              type: 'dropdownList',
              isMul: false,
              isMust: true
            },
            {
              compKey: 'compKey5',
              labelName: '创建时间：',
              codeField: 'startDate,endDate',
              component: () => import('@/components/org/datePicker/datePicker'),
              dateType: 'daterange',
              isMul: false, // 多选状态
              isMust: false // 收起状态
            }
          ],

      // 动态生成网格列
      tableCols:
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path] &&
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path].tableCols &&
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path].tableCols
          .length > 0
          ? this.$ConfigCache.CacheConfig.cacheData[this.$route.path].tableCols
          : [
            {
              prop: 'releaseId',
              label: '主键ID',
              hidden: true,
              alwaysHidden: true
            },
            {
              prop: 'updateControlIdO',
              label: '并发控制ID',
              hidden: true,
              alwaysHidden: true
            },
            {
              prop: 'transferOrderId',
              label: '展车主表id',
              hidden: true,
              alwaysHidden: true
            },
            {
              prop: 'controlBtn',
              label: '操作',
              minWidth: 180,
              isComponent: true,
              comps: [
                {
                  compKey: 'propKey1',
                  labelName: '编辑',
                  component: () => import('@/components/org/linkButton'),
                  clickEvent: (index) => this.edit(index),
                  rowFileds: 'show:transferOrderStatusCn-已录入'
                },
                {
                  compKey: 'propKey2',
                  labelName: '查看',
                  component: () => import('@/components/org/linkButton'),
                  clickEvent: (index) => {
                    this.viewData(index)
                  },
                  rowFileds: 'show:transferOrderStatusCn-已作废|已发布'
                }
              ]
            },
            {
              prop: 'transferOrderStatusCn',
              label: '订单状态'
            },
            {
              prop: 'transferOrderCode',
              label: '批次编号',
              width: 140
            },
            {
              prop: 'chargeMen',
              label: '负责人姓名'
            },
            {
              prop: 'chargePhone',
              label: '负责人电话',
              width: 140
            },
            {
              prop: 'creator',
              label: '创建人'
            },
            {
              prop: 'createdDate',
              label: '创建时间',
              width: 140
            },
            {
              prop: 'preNum',
              label: '计划配车数量'
            },
            {
              prop: 'reNum',
              label: '实际配车数量'
            },
            {
              prop: 'orderNum',
              label: '总计'
            },
            {
              prop: 'remark',
              label: '备注'
            }
          ],

      formField: this.$utils.getFormField(this, {
        chargeMen: '',
        chargePhone: '',
        orderState: '',
        startDate: '',
        endDate: '',
        transferOrderCode: '',
        updateControlIdO: ''
      }, this.$ConfigCache.CacheConfig.cacheData[viewPageCode]),

      // 单表格模版页面组件回调事件
      callbackObj: {
        // 当选择项发生变化时会触发该事件（多选时）
        onCheckSelectChange: (selection) => {
          this.selectRow = selection.map((item) => {
            return item.updateControlIdO
          })
          this.transferOrderId = selection.map((item) => {
            return item.transferOrderId
          })
          this.handleSelectionChange(selection)
        }
      }
    }
  },

  mounted() {
    // 列表查询
    this.queryTable(1)
  },

  methods: {
    // 发布
    issue() {
      this.$confirm('确定要发布吗?', '提示', {
        type: 'warning'
      }).then(() => {
        const queryObj = {
          type: 'mutation',
          apiConfig: api.publishExhibitionCarProduction,
          // 条件/实体参数（变量），根据typeParam中的定义配置
          variables: {
            transferOrderId: this.transferOrderId,
            updateControlIdO: this.selectRow
          }
        }
        // 转换了中台请求格式数据
        var paramD = this.$getParams(queryObj)
        this.$requestAPI(paramD).then((response) => {
          if (response.result === '1') {
            this.$message({
              message: response.msg
            })
          } else {
            this.$message({
              message: response.msg
            })
          }
          this.queryTable(1)
        })
      }).catch(err => {
        console.log(err)
      })
    },

    // 作废
    invalid() {
      // debugger
      this.$confirm('确定要作废吗?', '提示', {
        type: 'warning'
      }).then(() => {
        const queryObj = {
        // 保存需要传 type="mutation"
          type: 'mutation',
          apiConfig: api.cancelExhibitionCarProduction,
          // 条件/实体参数（变量），根据typeParam中的定义配置
          variables: {
            transferOrderId: this.transferOrderId,
            updateControlIdO: this.selectRow
          }
        }
        // 转换了中台请求格式数据
        var paramD = this.$getParams(queryObj)
        this.$requestAPI(paramD).then((response) => {
          if (response.result === '1') {
            this.$message({
              message: response.msg
            })
          } else {
            this.$message({
              message: response.msg
            })
          }
          this.queryTable(1)
        })
      }).catch(err => {
        console.log(err)
      })
    },

    // 选择列是否生效
    getSelectable(row, index) {
      if (row.transferOrderStatus === '1') {
        return true
      }
    },
    // 当选择项发生变化时会触发该事件
    handleSelectionChange(selection) {
      const btns = this.tableButtons.filter(o => o.disabled !== undefined)
      if (btns.length > 0) {
        const isCheck = selection && selection.length > 0
        btns.forEach((item) => {
          item.disabled = !isCheck
        })
      }
    },

    // 新增
    add() {
      this.showPopupsVisible = true
      this.editPopupsState = 'add'
      this.editRowData = { chargeMen: '', chargePhone: '', remark: '', transferOrderCode: '' }
    },

    // 编辑
    edit(index) {
      this.showPopupsVisible = true
      this.editPopupsState = 'edit'
      this.editRowData = this.$refs['multipleTable'].list[index]
    },

    viewData(index) {
      this.viewPopupsVisible = true
      this.editPopupsState = 'edit'
      this.viewRowData = this.$refs['multipleTable'].list[index]
    },

    // // 关闭资料查看弹窗
    closeviewData() {
      this.viewPopupsVisible = false
      this.viewPopupsKey = this.$utils.generateId()
    }
  }
}
</script>
